<template>
  <div class="order-page">
    <h2>我的订单</h2>

    <el-button type="primary" @click="openDialog()">新增订单</el-button>

    <el-table :data="orderList" style="width: 100%; margin-top: 20px">
  <el-table-column prop="id" label="订单id" />
  <el-table-column prop="orderName" label="订单名称" />
  <el-table-column prop="orderStarttime" label="开始时间" width="160" />
  <el-table-column prop="orderEndtime" label="结束时间" width="160" />
  <el-table-column prop="money" label="金额（元）" width="100" />
  <el-table-column prop="status" label="状态" width="100">
    <template #default="scope">
      <el-tag :type="scope.row.status === '已完成' ? 'success' : 'info'">{{ scope.row.status }}</el-tag>
    </template>
  </el-table-column>
  <el-table-column label="操作" width="260">
  <template #default="scope">
    <el-button type="primary" size="small" @click="openDialog(scope.row)">编辑</el-button>
    <el-button type="danger" size="small" @click="deleteOrder(scope.row.id)">删除</el-button>
    <el-button
      v-if="scope.row.status === '未完成'"
      type="success"
      size="small"
      @click="completeOrder(scope.row)"
    >完成</el-button>
  </template>
</el-table-column>

</el-table>


    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible" :title="form.id ? '编辑订单' : '新增订单'">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="订单名称" prop="order_name">
          <el-input v-model="form.order_name" />
        </el-form-item>
        <el-form-item label="金额" prop="money">
          <el-input-number v-model="form.money" :min="0" />
        </el-form-item>
        <el-form-item label="开始时间" prop="order_starttime">
          <el-date-picker v-model="form.order_starttime" type="datetime" placeholder="请选择开始时间" />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker v-model="form.order_endtime" type="datetime" placeholder="请选择结束时间" />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="form.status">
            <el-option label="未完成" value="未完成" />
            <el-option label="已完成" value="已完成" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.note" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveOrder">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/stores/userStore'
import { storeToRefs } from 'pinia'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'


const userStore = useUserStore()
const { id } = storeToRefs(userStore)

const orderList = ref([])
const dialogVisible = ref(false)
const form = ref({
  id: null,
  order_name: '',
  user_id: null,
  pet_kind: '',
  money: 0,
  order_starttime: '',
  order_endtime: '',
  note: '',
  status: '未完成'
})
const formRef = ref(null)

const rules = {
  order_name: [{ required: true, message: '请输入订单名称', trigger: 'blur' }],
  pet_kind: [{ required: true, message: '请选择宠物种类', trigger: 'change' }],
  order_starttime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  money: [{ required: true, message: '请输入金额', trigger: 'blur' }]
}

const loadOrders = async () => {
  if (!id.value) return
  try {
    const res = await axios.get(`/api/order/list?userId=${id.value}`)
    if (res.data.success) {
      orderList.value = res.data.data
    }
  } catch (e) {
    ElMessage.error('加载订单失败')
  }
}

const completeOrder = async (order) => {
  const updatedOrder = {
    ...order,
    status: '已完成',
    order_endtime: dayjs().format('YYYY-MM-DD HH:mm:ss')
  }

  const res = await axios.post('/api/order/update', updatedOrder)
  if (res.data.success) {
    ElMessage.success('订单已完成')
    await loadOrders()
  } else {
    ElMessage.error('操作失败')
  }
}
const openDialog = (row = null) => {
  if (row) {
    form.value = { ...row }
  } else {
    form.value = {
      id: null,
      order_name: '',
      user_id: id.value,
      pet_kind: '',
      money: 0,
      order_starttime: '',
      order_endtime: '',
      note: '',
      status: '未完成'
    }
  }
  dialogVisible.value = true
}

const saveOrder = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return

    form.value.user_id = id.value
    const url = form.value.id ? '/api/order/update' : '/api/order/add'
    const res = await axios.post(url, form.value)
    if (res.data.success) {
      ElMessage.success('保存成功')
      dialogVisible.value = false
      await loadOrders()
    } else {
      ElMessage.error(res.data.message || '保存失败')
    }
  })
}

const deleteOrder = async (orderId) => {
  const res = await axios.delete(`/api/order/delete/${orderId}`)
  if (res.data.success) {
    ElMessage.success('删除成功')
    await loadOrders()
  } else {
    ElMessage.error('删除失败')
  }
}

onMounted(() => {
  userStore.loadLocalStorage()
  loadOrders()
})
</script>

<style scoped>
.order-page {
  padding: 20px;
}
</style>
